package com.laikan.reader.bookreader.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookfriend.activity.RechargePage;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.RewardAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.RewardBean;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.*;

/**
 * 打赏页
 *
 * @author wxl
 */
@SuppressLint ("HandlerLeak")
public class RewardActivity extends BasicActivity implements OnClickListener {

    private TextView back_btn;
    private EditText num_edit;
    /*显示图标和数字的布局*/
    private RelativeLayout lin_01, lin_02, lin_03, lin_04, lin_05, lin_06, lin_07, lin_08;
    private TextView button_ok;
    private LinearLayout num_add, num_cut;
    private ImageView img_add, img_cut;
    private int type = 0;
    private String num, sum; //sum：共计结果 xxM
    private String sum_num; //加或减后的最终个数结果
    private String id, bookname, content;
    private EditText content_text;
    private ListView reward_list;
    private ArrayList<RewardBean> mRewardDataList;
    private RewardAdapter mAdapter;
    //    private PullToRefreshListView ptrLv;
    private int total;// 返回的数据总数
    private ImageView back_tv;
    private LinearLayout bottom_lin;
    private int rewardNumberInt = 0;
    //    private int readFlag = 1;
    private LinearLayout reward_bottom;
    private LinearLayout reward_top;
    private WindowManager wm; //获取窗口管理器
    private int scrWidth; // 屏幕宽
    private int scrHeight; // 屏幕高
    private Bitmap read_add_white, read_cut_white;
    Drawable drawable_add_gray, drawable_cut_gray;
    Drawable drawable_add_red, drawable_cut_red;
    Drawable drawable_back_tv;
    private RelativeLayout back_layout;
    /*只显示数字的布局*/
    private RelativeLayout lin001, lin002, lin003, lin004, lin005, lin006, lin007, lin008;
    private TextView tv001, tv002, tv003, tv004, tv005, tv006, tv007, tv008;
    private String item_num; //每个item对应的数据
    private LinearLayout reward_none;
    private float y = 0;

    private TouchSwipeRefreshLayout mRewardSwipeRefresh;
    private int mCurrentPage = 1;
    private int END_LIST_PAGE = -1;
    private boolean mIsPullDown = true;// 是否下拉
    private long mLoadMoreInternalTime;
    private ProgressBar_Modern mModernLoadProgressBar;
    private HashSet mRewardIdList = new HashSet();
    private int PAGE_LIMIT_SIZE = 10;
    private String totalSize;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_reward1_new);
        reward_none = (LinearLayout)findViewById(R.id.reward_none);
        button_ok = (TextView)findViewById(R.id.button_ok);
        lin001 = (RelativeLayout)findViewById(R.id.lin001);
        lin002 = (RelativeLayout)findViewById(R.id.lin002);
        lin003 = (RelativeLayout)findViewById(R.id.lin003);
        lin004 = (RelativeLayout)findViewById(R.id.lin004);
        lin005 = (RelativeLayout)findViewById(R.id.lin005);
        lin006 = (RelativeLayout)findViewById(R.id.lin006);
        lin007 = (RelativeLayout)findViewById(R.id.lin007);
        lin008 = (RelativeLayout)findViewById(R.id.lin008);

        tv001 = (TextView)findViewById(R.id.tv001);
        tv002 = (TextView)findViewById(R.id.tv002);
        tv003 = (TextView)findViewById(R.id.tv003);
        tv004 = (TextView)findViewById(R.id.tv004);
        tv005 = (TextView)findViewById(R.id.tv005);
        tv006 = (TextView)findViewById(R.id.tv006);
        tv007 = (TextView)findViewById(R.id.tv007);
        tv008 = (TextView)findViewById(R.id.tv008);

        content_text = (EditText)findViewById(R.id.content_text);
        bottom_lin = (LinearLayout)findViewById(R.id.bottom_lin);
        reward_list = (ListView)findViewById(R.id.reward_list);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_btn = (TextView)findViewById(R.id.back_btn);

        reward_bottom = (LinearLayout)findViewById(R.id.reward_bottom);
        reward_top = (LinearLayout)findViewById(R.id.reward_top);
        mRewardSwipeRefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        mRewardSwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);

        mModernLoadProgressBar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);

        item_num = "10";
        type = 1;
        changeTextColor(tv001);
        changeBorderColor(lin001);
    }

    /**
     * 设置reward布局的尺寸
     */
    private void setReward() {
        //获取屏幕宽度
        wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        scrWidth = wm.getDefaultDisplay().getWidth();
        scrHeight = wm.getDefaultDisplay().getHeight();
        int width = scrWidth / 4;
        //动态设置控件的大小
        reward_bottom.setLayoutParams(new LinearLayout.LayoutParams(scrWidth, width));
        reward_top.setLayoutParams(new LinearLayout.LayoutParams(scrWidth, width));
    }

    /**
     * 初始化代码设置图片颜色
     */

    public void initBmp() {
        read_add_white = PublicUtil.readBitMap(this, R.drawable.reward_num_add_bg);
        read_cut_white = PublicUtil.readBitMap(this, R.drawable.reward_num_cut_bg);
        drawable_add_gray = new BitmapDrawable(PublicUtil.getAlphaBitmap(read_add_white, Color.parseColor("#999999")));
        drawable_cut_gray = new BitmapDrawable(PublicUtil.getAlphaBitmap(read_cut_white, Color.parseColor("#999999")));
        drawable_add_red = new BitmapDrawable(PublicUtil.getAlphaBitmap(read_add_white, Color.parseColor("#66ccdd")));
        drawable_cut_red = new BitmapDrawable(PublicUtil.getAlphaBitmap(read_cut_white, Color.parseColor("#66ccdd")));
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        id = getIntent().getStringExtra("bookId");
        bookname = getIntent().getStringExtra("bookName");
        back_btn.setText(bookname);
        mRewardDataList = new ArrayList<RewardBean>();
        mAdapter = new RewardAdapter(mContext, mRewardDataList);
        reward_list.setAdapter(mAdapter);
        //        readFlag = getIntent().getIntExtra("readFlag", 1);
        getData(true);
    }

    private void getData(boolean flag) {
        if (flag) {
            showDialog();
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "1");
        map.put("pageNo", mCurrentPage + "");
        map.put("pageSize", PAGE_LIMIT_SIZE + "");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mRewardSwipeRefresh.setRefreshing(false);
                mRewardSwipeRefresh.setLoading(false);
                closeLoadMoreView(System.currentTimeMillis());
                dismissDialog();
                BaseDataBean<BaseListDataBean<RewardBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<RewardBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (null == result || null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                        ToastMgr.showShortToast(result.getError_msg());
                    }else if (null == result.getData().getData() || !(result.getData().getData().size() > 0)) {
                        //                        ptrLv.setPullToRefreshEnabled(false);
                        reward_none.setVisibility(View.VISIBLE);
                    }else {
                        reward_none.setVisibility(View.GONE);
                        if (mIsPullDown) {
                            // 下拉刷新
                            mAdapter.setDatas(updateListData(result.getData().getData()));
                        }else {
                            // 上拉加载,数据追加
                            mAdapter.setDatas(loadMoreData(result.getData().getData()));
                        }
                        getCurrentPage(result.getData().getTotal());
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mRewardSwipeRefresh.setRefreshing(false);
                mRewardSwipeRefresh.setLoading(false);
                closeLoadMoreView(System.currentTimeMillis());
                dismissDialog();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。51");
            }

            @Override
            public void onFinish() {
                mRewardSwipeRefresh.setRefreshing(false);
                mRewardSwipeRefresh.setLoading(false);
                closeLoadMoreView(System.currentTimeMillis());
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_reward + id + "?type=1&pageNo=" + mCurrentPage + "&pageSize=10");
//        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.laikan_get_reward + id + "?type=1&pageNo=" + mCurrentPage + "&pageSize=10", null, null, requestListener);
    }

    /**
     * @param totalSize
     */
    public void getCurrentPage(String totalSize) {
        this.totalSize = totalSize;
        mCurrentPage = mRewardDataList.size() / PAGE_LIMIT_SIZE + 1;
        total = Integer.parseInt(PublicUtil.isNum(totalSize));
        if (mRewardDataList.size() >= total) {
            mCurrentPage = END_LIST_PAGE;
        }
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        button_ok.setOnClickListener(this);
        lin001.setOnClickListener(this);
        lin002.setOnClickListener(this);
        lin003.setOnClickListener(this);
        lin004.setOnClickListener(this);
        lin005.setOnClickListener(this);
        lin006.setOnClickListener(this);
        lin007.setOnClickListener(this);
        lin008.setOnClickListener(this);
        content_text.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(content_text.getWindowToken(), 0);
                }
            }
        });

        reward_list.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        y = motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mRewardDataList.size() == 0) {
                            bottom_lin.setVisibility(View.VISIBLE);
                        }else if (mRewardDataList.size() > 0) {
                            if (motionEvent.getY() > y) {
                                bottom_lin.setVisibility(View.VISIBLE);
                            }else {
                                bottom_lin.setVisibility(View.GONE);
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return false;
            }
        });

        mRewardSwipeRefresh.setChildView(reward_list);
        mRewardSwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                mIsPullDown = true;
                getData(false);

            }
        });

        mRewardSwipeRefresh.setOnLoadListener(new TouchSwipeRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                KLog.e(" mRewardSwipeRefresh setOnLoadListener");
                mRewardSwipeRefresh.setRefreshing(false);
                if (END_LIST_PAGE == mCurrentPage) {
                    ToastMgr.showShortToast(R.string.fw_data_loading_done);
                    mRewardSwipeRefresh.setLoading(false);
                    return;
                }else {
                    mModernLoadProgressBar.setVisibility(View.VISIBLE);
                    mLoadMoreInternalTime = System.currentTimeMillis() + 2000;
                    mIsPullDown = false;
                    getData(false);
                }
            }
        });
    }

    public void closeLoadMoreView(long currenttime) {
        if (currenttime < mLoadMoreInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mModernLoadProgressBar.setVisibility(View.GONE);
                }
            }, 1000);
        }else {
            mModernLoadProgressBar.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //        num_edit.clearFocus();
    }

    @Override
    public void onClick(View v) {
        content_text.clearFocus();//手动清除焦点(即设置焦点复位)
        switch (v.getId()) {
            case R.id.content_text:
                break;
            case R.id.num_add:
                break;
            case R.id.num_cut:
                break;
            case R.id.back_layout:
                content_text.clearFocus();
                finish();
                break;
            case R.id.lin001:
                item_num = "10";
                type = 1;
                changeTextColor(tv001);
                changeBorderColor(lin001);
                break;
            case R.id.lin002:
                item_num = "1";
                type = 2;
                changeTextColor(tv002);
                changeBorderColor(lin002);
                break;
            case R.id.lin003:
                item_num = "1";
                type = 3;
                changeTextColor(tv003);
                changeBorderColor(lin003);
                break;
            case R.id.lin004:
                item_num = "1";
                type = 4;
                changeTextColor(tv004);
                changeBorderColor(lin004);
                break;
            case R.id.lin005:
                item_num = "1";
                type = 5;
                changeTextColor(tv005);
                changeBorderColor(lin005);
                break;
            case R.id.lin006:
                item_num = "1";
                type = 6;
                changeTextColor(tv006);
                changeBorderColor(lin006);
                break;
            case R.id.lin007:
                item_num = "1";
                type = 7;
                changeTextColor(tv007);
                changeBorderColor(lin007);
                break;
            case R.id.lin008:
                item_num = "1";
                type = 8;
                changeTextColor(tv008);
                changeBorderColor(lin008);
                break;
            case R.id.button_ok:
                if (ActivityUitl.isNetworkAvailable(mContext)) {
                    if (null == SPUtil.getString("user_id", "") || "0".equals(SPUtil.getString("user_id", "")) || "".equals(SPUtil.getString("user_id", ""))) {
                        Intent intent = new Intent(this, LoginActivity.class);
                        startActivity(intent);
                    }else {
                        submit();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void submit() {
        showDialog();
        num = item_num;
        content = content_text.getText().toString().trim();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("type", type + "");
        map.put("count", num);
        map.put("content", content);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                dismissDialog();
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (obj != null) {
                        if (null == obj.getString("data") || !Constants.RESULT_OK.equals(result)) {
                            if ("102".equals(obj.getString("error_no"))) {
                                showPickDialog();
                            }
                        }else {
                            if (Constants.RESULT_OK.equals(result)) {
                                ToastMgr.showShortToast(R.string.reward_success);
                                mCurrentPage = 1;
                                mIsPullDown = true;
                                content_text.setText("");
                                content_text.setHint(R.string.reward_edit_content);
                                SPUtil.putBoolean("reward_refresh", true);
                                getData(true);
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (JSONException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                dismissDialog();
                ToastMgr.showShortToast("与服务器连接失败");
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_detail + id + "/donate?");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_detail + id + "/donate?", map, null, null, requestListener);
    }

    /**
     * 显示选择充值的对话框
     */
    private void showPickDialog() {
        AlertDialog mdialog = new AlertDialog.Builder(mContext).setView(View.inflate(mContext, R.layout.alterdialog, null)).setNegativeButton("充值", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(mContext, RechargePage.class);
                startActivity(intent);
            }
        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    private void changeColor(RelativeLayout layout) {
        List<RelativeLayout> layoutList = new ArrayList<RelativeLayout>();
        layoutList.add(lin_01);
        layoutList.add(lin_02);
        layoutList.add(lin_03);
        layoutList.add(lin_04);
        layoutList.add(lin_05);
        layoutList.add(lin_06);
        layoutList.add(lin_07);
        layoutList.add(lin_08);
        for (int i = 0; i < layoutList.size(); i++) {
            if (layoutList.get(i).equals(layout)) {
                layoutList.get(i).setBackgroundColor(getResources().getColor(R.color.C_EEEEEE));
            }else {
                layoutList.get(i).setBackgroundColor(getResources().getColor(R.color.C_FFFFFF));
            }
        }
    }

    private ArrayList<RewardBean> updateListData(ArrayList<RewardBean> list) {
        ArrayList<RewardBean> refreshList = new ArrayList<RewardBean>();
        for (int i = 0; i < list.size(); i++) {
            if (!mRewardIdList.contains(list.get(i).getId())) {
                mRewardIdList.add(list.get(i).getId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(mRewardDataList);
        mRewardDataList.clear();
        mRewardDataList.addAll(refreshList);
        refreshList.clear();
        return mRewardDataList;
    }

    private ArrayList<RewardBean> loadMoreData(ArrayList<RewardBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (!mRewardIdList.contains(list.get(i).getId())) {
                mRewardIdList.add(list.get(i).getId());
                mRewardDataList.add(list.get(i));
            }
        }
        return mRewardDataList;
    }

    /**
     * 更改字体颜色
     *
     * @param tv
     */
    private void changeTextColor(TextView tv) {
        List<TextView> tvList = new ArrayList<TextView>();
        tvList.add(tv001);
        tvList.add(tv002);
        tvList.add(tv003);
        tvList.add(tv004);
        tvList.add(tv005);
        tvList.add(tv006);
        tvList.add(tv007);
        tvList.add(tv008);
        for (int i = 0; i < tvList.size(); i++) {
            if (tvList.get(i).equals(tv)) {
                tvList.get(i).setTextColor(getResources().getColor(R.color.C_66ccdd));
            }else {
                tvList.get(i).setTextColor(getResources().getColor(R.color.C_999999));
            }
        }
    }

    /**
     * 更改布局边框颜色
     *
     * @param layout
     */
    private void changeBorderColor(RelativeLayout layout) {
        List<RelativeLayout> layoutList = new ArrayList<RelativeLayout>();
        layoutList.add(lin001);
        layoutList.add(lin002);
        layoutList.add(lin003);
        layoutList.add(lin004);
        layoutList.add(lin005);
        layoutList.add(lin006);
        layoutList.add(lin007);
        layoutList.add(lin008);
        for (int i = 0; i < layoutList.size(); i++) {
            if (layoutList.get(i).equals(layout)) {
                layoutList.get(i).setBackgroundResource(R.drawable.lk_reward_bg_seleted);
            }else {
                layoutList.get(i).setBackgroundResource(R.drawable.lk_reward_bg_unseleted);
            }
        }
    }
}
